package com.itheima.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.User;
import com.itheima.domain.UserExample;
import com.itheima.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Reference
    private IUserService userService;

    /**
     * 显示
     * @param request
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(HttpServletRequest request, 
        @RequestParam(defaultValue = "1") int page, 
        @RequestParam(defaultValue = "10") int pageSize) {
        UserExample userExample = new UserExample();
        PageInfo<User> all = userService.findAll(userExample, page, pageSize);
        request.setAttribute("pageInfo", all);
        return "/user/user-list";
    }

    /**
     * 修改
     * @param user
     * @return
     */
    @RequestMapping("/edit")
    public String edit(User user) {
        if (StringUtils.isEmpty(user.getId())) {
            user.setId(UUID.randomUUID().toString());
            userService.add(user);
        } else {
            userService.update(user);
        }
        return "redirect:/user/findAll.do";
    }

    /**
     * 更新
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(HttpServletRequest request, String id) {
        User user = userService.findById(id);
        request.setAttribute("user", user);
        return "/user/user-edit";
    }

}
